import request from '@/utils/request'
import { LoginAction, RootThunkAction } from '@/types/store'
import { ApiResponse, LoginForm, Token } from '@/types/data'
import { removeToken, setToken } from '@/utils/storage'

export const login = (data:LoginForm):RootThunkAction => {
  return async (dispatch) => {
    const res = await request.post<ApiResponse<Token>>('/authorizations', data)

    // 本地持久化
    setToken(res.data.data)
    dispatch({
      type: 'login/token',
      payload: res.data.data
    })
  }
}

// 请求发送验证码
export const getCode = (mobile:string) => {
  return async () => {
    await request.get(`/sms/codes/${mobile}`)
  }
}

export const logout = ():LoginAction => {
  removeToken()
  return {
    type: 'login/logout'
  }
}

export function saveToken (token: Token) : LoginAction {
  // 1. 本地持久化
  setToken(token)

  // 2. 保存token
  return {
    type: 'login/token',
    payload: token
  }
}
